# encoding = utf-8
class ArticlesController < ApplicationController

  before_filter :authenticate_admin!, :only => [:new, :create, :list, :edit, :update, :delete]

  def new
    @article = Article.new
    @categories = Category.all
    @action = {:action => 'create'}
    @action_title = '添加新文章'
    render :layout => 'admins'
  end

  def create
    @article = Article.new(params[:article])

    if @article.save
      flash[:success] = '添加文章成功'
      redirect_to :action => "list"
    else
      @categories = Category.all
      @action = {:action => 'create'}
      flash[:error] = @article.errors
      render :layout => 'admins', :action => 'new'
    end
  end

  def list
    @articles = Article.order('created_at desc').paginate :page => params[:page], :per_page => PAGE_SIZE
    render :layout => 'admins'
  end

  def edit
    @article = Article.find(params[:id])
    @categories = Category.all
    @action = {:action => 'update', :id => @article.id}
    @action_title = '编辑文章'
    render :layout => 'admins', :action => 'new'
  end

  def update
    article = Article.update(params[:id], params[:article])
    if article
      flash[:success] = '文章更新成功'
    else
      flash[:error] = '文章更新失败'
    end
    redirect_to :action => "list"
  end

  def delete
    article = Article.find(params[:id])
    if article.destroy
      flash[:success] = '文章删除成功'
    end
    redirect_to :action => "list"
  end
  
end
